layui.use(['laydate', 'layer', 'form', 'table', 'configs', 'template','excel'], function () {
  var $ = layui.jquery,
      laydate = layui.laydate,
      layer = layui.layer,
      form = layui.form,
      table = layui.table,
      template = layui.template,
      config = layui.configs,
      excel = layui.excel;
  var tableRender = null;
  var areaId = null;
  initAll();
  
  function initAll(){
    getArea();
    initDate();
  }


  // 查马达
/*  function getMotors() {
    $.ajax({
      url: config.motorBaseUrl + "/mo_motors/selectMortorAll/v1.0",
      type: "post",
      datatype: "json",
      data: {},
      success: function (result) {
        if (result.stateCode == 0) {
          $(".motorMenu").html(template("motors-tpl", result));
          $(".searchBtn").click();
          form.render('select');
        } else {
          layer.msg(result.stateMsg);
        }
      }
    })
  }*/
  
  //监听所选马达
  // var motorsTitle = [];
  // var motorsId = [];
  // form.on('checkbox(motorMenu)', function (data) {
  //   var title = $(data.elem).attr("title");
  //   if (data.elem.checked) {
  //     motorsTitle.push(title);
  //     motorsId.push(data.value);
  //   } else {
  //     motorsTitle = motorsTitle.filter(function (item) {
  //       return item != title;
  //     });
  //     motorsId = motorsId.filter(function (item) {
  //       return item != data.value;
  //     });
  //   }
  //   var title = motorsTitle.join(",");
  //   $(".optval").attr("value", title);
  //   $(".optval").attr("motorsId", motorsId);
  // });
  
  function initDate(startValue){
    var st = new Date(new Date().getTime() - 300*1000*5 );
    startValue = startValue || st;
    laydate.render({
      elem: '#startDate',
      value: startValue,
      format: 'yyyy-MM-dd HH:mm:ss',
      type: 'datetime',
      max: formatDate()
    });
    laydate.render({
      elem: '#endDate',
      value: new Date(),
      format: 'yyyy-MM-dd HH:mm:ss',
      type: 'datetime',
      max: formatDate()
    });
  };

  //获取区域
  function getArea() {
    $.ajax({
      url: config.motorBaseUrl + "/area_info/select/v1.0",
      type: "post",
      datatype: "json",
      data: {},
      success: function (result) {
        if (result.stateCode == 0) {
          $(".areaMenu").html(template("motor-areas-tpl", result));
          form.render('select');
          //监听区域选择
          form.on('select(areaMenu)', function(data) {
            $(".troughMenu").html("");
            $(".motorMenu").html('<option value="0">全部</option>');
            areaId = data.value;
            getTrough(areaId);
          });
        } else {
          layer.alert(result.stateMsg);
        }
      }
    })
  }

  //按区域查槽位
  function getTrough(areaId) {
    $.ajax({
      url: config.motorBaseUrl + "/mo_trough/selectAreaTrough/v1.0",
      type: "post",
      datatype: "json",
      data: {
        areaId: areaId
      },
      success: function (result) {
        if (result.stateCode == 0) {
          $(".troughMenu").html(template("motor-trough-tpl", result));
          form.render('select');
          //监听槽位选择
          form.on('select(troughMenu)', function(data) {
            $(".motorMenu").html("");
            var troughId = data.value;
            getMotors(troughId);
          });
        } else {
          layer.alert(result.stateMsg);
        }
      }
    })
  };

  // 按槽位查马达
  function getMotors(troughId) {
    $.ajax({
      url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
      type: "post",
      datatype: "json",
      data: {
        troughId: troughId
      },
      success: function (result) {
        if (result.stateCode == 0) {
          $(".motorMenu").html(template("motors-tpl", result));
          form.render('select');
        } else {
          layer.msg(result.stateMsg);
        }
      }
    })
  }
  
  //查询
  $(".searchBtn").click(function () {
    // $(".reportTable").append('<i class="layui-icon layui-icon-loading layui-anim-rotate layui-anim-loop"></i>');
    form.on('submit(search)', function(data){
      // var tableData = {
      //   type: data.field.type,
      //   mo_id: data.field.mo_id,
      //   startTime: data.field.startTime,
      //   endTime: data.field.endTime
      // };
      getTableData(data.field);
      return false;
    });
  });

  //类型变化，开始时间变化
  form.on('select(timeType)', function(data){
    var startValue;
    switch (data.value) {
      case "0": //5min*5
        startValue = new Date(new Date().getTime() - 300*1000*5 );
        break;
      case "1": //1H*5
        startValue = new Date(new Date().getTime() - 3600*1000*5 );
        break;
      case "2": //24H*5
        startValue = new Date(new Date().getTime() - 3600*24*1000*5 );
        break;
      default:
        startValue = new Date(new Date().getTime() - 300*1000*5 );
    }
    initDate(startValue);
  });

  //表格数据
/*  function getTableData(data) {
    $.ajax({
      url: config.motorBaseUrl + "/mo_data_report/select/v1.0",
      type: "post",
      datatype: "json",
     contentType: 'application/json;charset=UTF-8',
      data: {
        "type" :data.type,
        "mo_id" : data.mo_id,
        "startTime" : data.startTime,
        "endTime" : data.endTime
      },
      success: function (result) {
        if (result.stateCode == 0) {
          renderTable(result.data);
        } else {
          layer.msg(result.stateMsg);
        }
      }
    })
  }*/

  //获取表格数据
  function getTableData(data) {
    $.ajax({
      url: config.motorBaseUrl + "/mo_data_report/select/v1.0",
      type: "post",
      contentType: 'application/json;charset=UTF-8',
      datatype: "json",
      data: JSON.stringify(data),
      success: function (result) {
        if (result.stateCode == 0) {
          renderTable(result.data);
        } else {
          layer.msg(result.stateMsg);
        }
      }
    })
  }
  
  //渲染表格
  function renderTable(data) {
    tableRender = table.render({
      elem: '.reportTable'
      , id:"motorRecord"
      , data: data
      , cols: [[
        {field: 'strType', title: '报表类型'}
        ,{field: 'area_name', title: '区域'}
        ,{field: 'trough_name', title: '槽位'}
        ,{field: 'mo_name', title: '马达名称'}
        ,{field: 'strtime_area', title: '报表时间'}
        /*, {field: 'strtime_area', title: '启停信号'}*/
        , {field: 'avg_data', title: '当前值'}
      ]]
      // ,overflow: {
      //   type: 'tips'
      //   ,color: 'black' // 字体颜色
      //   ,bgColor: 'white' // 背景色
      // }
      , page: {
        layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
        , groups: 1 //只显示 5 个连续页码
        , first: false
        , last: false
        , limits: [10, 20, 50, 100, 500]
      }
      , limit: 10
      , loading: true
      , done: function (res) {
        //soulTable.render(this);
      }
    });
  }

  //导出
  $(".exportBtn").on("click",function () {
    excel.exportTable2Excel(tableRender, "马达振动记录");
   /* var st = new Date();
    console.log("st="+st);
    soulTable.export(tableRender, {
      filename: '马达振动记录.xlsx', // 文件名
    });
    var et = new Date();
    console.log("et="+et);
    console.log(et - st);*/
  });
});